﻿using FlyingEye.Consts;
using FlyingEye.Models;
using Microsoft.Extensions.Logging;
using Volo.Abp.Application.Services;

namespace OpenId2Ids
{
    public class ControllerActionWrapperService : ApplicationService
    {
        private readonly ILogger<ControllerActionWrapperService> _logger;

        public ControllerActionWrapperService(ILogger<ControllerActionWrapperService> logger)
        {
            _logger = logger;
        }

        public async Task<DefaultActionResult<TResult>> InvokeAsync<TResult>(Func<Task<TResult>> func)
        {
            try
            {
                var result = await func.Invoke();

                return DefaultActionResult<TResult>.GetSuccessResult(result);
            }
            catch (InvalidOperationException ex)
            {
                return DefaultActionResult<TResult>.GetFailureResult(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ApplicationConsts.Error);

                return DefaultActionResult<TResult>.GetFailureResult(ApplicationConsts.Error);
            }
        }

        public async Task<DefaultActionResult> InvokeAsync(Func<Task> action)
        {
            try
            {
                await action.Invoke();

                return DefaultActionResult.GetSuccessResult();
            }
            catch (InvalidOperationException ex)
            {
                return DefaultActionResult.GetFailureResult(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ApplicationConsts.Error);

                return DefaultActionResult.GetFailureResult(ApplicationConsts.Error);
            }
        }
    }
}
